
var gs3 = require('gs3');
var Utilities = gs3.Utilities;
var Entity = gs3.Models.Entity;
var Person_Management = gs3.Modules.HR.Person_Management;

var db_config = require('./db_config');

var table = {
    tableName: 'user',
    primary: 'id'
};

User_Management_Impl = new Person_Management(db_config, table);

module.exports = User_Management_Impl;

// TODO: create User_Management_Impl override methods below as needed

User_Management_Impl.modifyResponseOnAllSelectMethods = function(data) {
    //  do not allow password to be included in the responses
    if (data.Password) {
        delete data.Password;
    } else if (data.password) {
        delete data.password;
    }

    return data;
};

/**
 * @override
 * @param {type} person
 * @param {type} callback
 * @returns {undefined}
 */
User_Management_Impl.register = function(person, callback) {
    //  validations
    if (typeof callback !== 'function') {
        //  since the error cannot be handled because of the absence of a callback
        //  function, just throw the error.
        throw new Error("Invalid callback passed to list (Person_Management) - " + utilities.getDateTime());
    }

    var personEntity = this.createEntityFromObject(person);

    //  Override purpose
    //  the password field should be encrypted
    if (personEntity.fields.Password) {
        personEntity.fields.Password = Utilities.getMD5(personEntity.fields.Password);
    } else if (personEntity.fields.password) {
        personEntity.fields.password = Utilities.getMD5(personEntity.fields.password);
    }   

    var db = this.database;
    db.connect();
    db.insert(personEntity, function(err, data) {
        if (err) {
            callback(err, 'Error');
        } else {
            callback(err, data);
        }

        db.disconnect();
    });
};

User_Management_Impl.modify = function(person, callback) {
    //  validations
    if (typeof callback !== 'function') {
        //  since the error cannot be handled because of the absence of a callback
        //  function, just throw the error.
        throw new Error("Invalid callback passed to list (Person_Management) - " + utilities.getDateTime());
    }

    var personEntity = this.createEntityFromObject(person);

    //  Override purpose
    //  the password field should be encrypted
    if (personEntity.fields.Password) {
        personEntity.fields.Password = Utilities.getMD5(personEntity.fields.Password);
    } else if (person.fields.password) {
        personEntity.fields.password = Utilities.getMD5(personEntity.fields.password);
    }

    var db = this.database;
    db.connect();
    db.update(personEntity, function(err, data) {
        if (err) {
            callback(err, 'Error');
        } else {
            callback(err, data);
        }

        db.disconnect();
    });
};
